﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

using WCFMINERP.SharpZipLib;
using WCFMINERP.Contracts.DataContracts;

namespace WCFMINERP.Update
{
    public partial class FrmUpdate : Form
    {
        public delegate void UpdateCompleteHander();
        UpdateCompleteHander updateDelegete;
        private TransferFileInfo _tranFileInfo = null;
        private double _currentClientVersion;

        public FrmUpdate(TransferFileInfo tranfile,double currentClientVersion)
        {
            InitializeComponent();
            _tranFileInfo = tranfile;
            _currentClientVersion = currentClientVersion;

        }

        private void FrmUpdate_Load(object sender, EventArgs e)
        {


            Thread thUpdate = new Thread(DownloadFile);
            thUpdate.Start();
            //DownloadFile();
        }
        private void DownloadFile()
        {

            string fileName = Application.StartupPath + "\\" + _tranFileInfo.Name;
            File.WriteAllBytes(fileName, _tranFileInfo.Data);

            string[] filePath = new string[2];
            filePath[0] = fileName;
            string appPath = Application.StartupPath;
            string tgtDir = filePath[1] = appPath + "\\updata";
           
            //UnZipClass unzip = new UnZipClass();
            //unzip.UnZip(filePath);
            //UnZipClass.UnZip(fileName, Application.StartupPath);
            UnZipClass.ExtractZip(fileName, tgtDir);
            DirectoryInfo dir = new DirectoryInfo(tgtDir);

            FileInfo[] fileArry = dir.GetFiles();
            foreach (FileInfo file in fileArry)
            {
                //string fileOld=appPath+"\\"+file.Name;
                //if (File.Exists(fileOld))
                //{
                //    File.Delete(fileOld);
                //}
                //File.Copy(file.FullName, fileOld);
            }
            
            File.Delete(fileName);
            UpdateComplete();
        }
        
        private void UpdateComplete()
        {
            if (this.InvokeRequired)
            {
                updateDelegete = new UpdateCompleteHander(UpdateComplete);
                this.Invoke(updateDelegete);
            }
            else
            {
                string xmlPath = Application.StartupPath + "\\ShopParameters.xml";
                XMLOperator.UpdateNodesValue(@"ShopParameters/ClientVersion", xmlPath, _currentClientVersion.ToString());
                MessageBox.Show("更新完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            } 
        }
    }
}
